<template>
  <el-dialog
    v-model="dialogVisible"
    title="高级搜索"
    width="900px"
    :before-close="handleClose"
  >
    <div class="advanced-search">
      <el-form
        ref="formRef"
        :model="searchForm"
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关键词搜索">
              <el-input
                v-model="searchForm.keyword"
                placeholder="搜索评论内容、用户名等"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评论内容">
              <el-input
                v-model="searchForm.content"
                placeholder="搜索评论内容"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="用户ID">
              <el-input-number
                v-model="searchForm.userId"
                :min="1"
                placeholder="请输入用户ID"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input
                v-model="searchForm.userName"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="文章ID">
              <el-input-number
                v-model="searchForm.articleId"
                :min="1"
                placeholder="请输入文章ID"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input
                v-model="searchForm.ipAddress"
                placeholder="请输入IP地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="评论状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择评论状态"
                clearable
              >
                <el-option label="待审核" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
                <el-option label="已删除" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="敏感评论">
              <el-select
                v-model="searchForm.isSensitive"
                placeholder="请选择"
                clearable
              >
                <el-option label="非敏感" :value="0" />
                <el-option label="敏感评论" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="敏感词类型">
              <el-select
                v-model="searchForm.sensitiveType"
                placeholder="请选择敏感词类型"
                clearable
              >
                <el-option
                  v-for="type in sensitiveTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="点赞数范围">
              <div class="range-input">
                <el-input-number
                  v-model="searchForm.minLikeCount"
                  :min="0"
                  placeholder="最小值"
                  style="width: 45%"
                />
                <span style="margin: 0 10px">-</span>
                <el-input-number
                  v-model="searchForm.maxLikeCount"
                  :min="0"
                  placeholder="最大值"
                  style="width: 45%"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回复数范围">
              <div class="range-input">
                <el-input-number
                  v-model="searchForm.minReplyCount"
                  :min="0"
                  placeholder="最小值"
                  style="width: 45%"
                />
                <span style="margin: 0 10px">-</span>
                <el-input-number
                  v-model="searchForm.maxReplyCount"
                  :min="0"
                  placeholder="最大值"
                  style="width: 45%"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排序字段">
              <el-select
                v-model="searchForm.sortField"
                placeholder="请选择排序字段"
              >
                <el-option label="创建时间" value="create_time" />
                <el-option label="更新时间" value="update_time" />
                <el-option label="点赞数" value="like_count" />
                <el-option label="回复数" value="reply_count" />
                <el-option label="敏感度评分" value="sensitive_score" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序方向">
              <el-radio-group v-model="searchForm.sortOrder">
                <el-radio :value="'desc'">降序</el-radio>
                <el-radio :value="'asc'">升序</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="高级选项">
              <el-checkbox-group v-model="searchForm.advancedOptions">
                <el-checkbox label="onlyTopLevel">仅顶级评论</el-checkbox>
                <el-checkbox label="includeChildren">包含子评论</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="每页数量">
              <el-input-number
                v-model="searchForm.size"
                :min="10"
                :max="100"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="searching" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { type CommentListQuery } from "@/api/comment-management";

// Props
interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  search: [params: CommentListQuery];
}>();

// 响应式数据
const formRef = ref();
const searching = ref(false);

const searchForm = reactive({
  keyword: "",
  content: "",
  userId: undefined,
  userName: "",
  articleId: undefined,
  ipAddress: "",
  status: undefined,
  isSensitive: undefined,
  sensitiveType: undefined,
  dateRange: null,
  minLikeCount: undefined,
  maxLikeCount: undefined,
  minReplyCount: undefined,
  maxReplyCount: undefined,
  sortField: "create_time",
  sortOrder: "desc",
  advancedOptions: [],
  size: 20
});

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const sensitiveTypes = [
  { label: "政治敏感", value: "政治" },
  { label: "违禁内容", value: "违禁词" },
  { label: "广告内容", value: "广告" },
  { label: "色情内容", value: "色情" },
  { label: "暴力内容", value: "暴力" }
];

// 表单验证规则
const formRules = {
  ipAddress: [
    {
      pattern: /^(\d{1,3}\.){3}\d{1,3}$/,
      message: "请输入正确的IP地址格式",
      trigger: "blur"
    }
  ]
};

// 方法
const handleSearch = async () => {
  try {
    if (
      searchForm.ipAddress &&
      !formRules.ipAddress[0].pattern.test(searchForm.ipAddress)
    ) {
      ElMessage.error("请输入正确的IP地址格式");
      return;
    }

    searching.value = true;

    const params: CommentListQuery = {
      current: 1,
      size: searchForm.size,
      sortField: searchForm.sortField,
      sortOrder: searchForm.sortOrder as "asc" | "desc"
    };

    // 设置搜索参数
    if (searchForm.keyword) params.keyword = searchForm.keyword;
    if (searchForm.content) params.content = searchForm.content;
    if (searchForm.userId) params.userId = searchForm.userId;
    if (searchForm.userName) params.userName = searchForm.userName;
    if (searchForm.articleId) params.articleId = searchForm.articleId;
    if (searchForm.ipAddress) params.ipAddress = searchForm.ipAddress;
    if (searchForm.status !== undefined) params.status = searchForm.status;
    if (searchForm.isSensitive !== undefined)
      params.isSensitive = searchForm.isSensitive;
    if (searchForm.sensitiveType)
      params.sensitiveType = searchForm.sensitiveType;
    if (searchForm.minLikeCount !== undefined)
      params.minLikeCount = searchForm.minLikeCount;
    if (searchForm.maxLikeCount !== undefined)
      params.maxLikeCount = searchForm.maxLikeCount;
    if (searchForm.minReplyCount !== undefined)
      params.minReplyCount = searchForm.minReplyCount;
    if (searchForm.maxReplyCount !== undefined)
      params.maxReplyCount = searchForm.maxReplyCount;

    // 设置时间范围
    if (searchForm.dateRange) {
      params.startTime = searchForm.dateRange[0];
      params.endTime = searchForm.dateRange[1];
    }

    // 设置高级选项
    params.onlyTopLevel = searchForm.advancedOptions.includes("onlyTopLevel");
    params.includeChildren =
      searchForm.advancedOptions.includes("includeChildren");

    emit("search", params);
    handleClose();
    ElMessage.success("搜索条件已应用");
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败");
  } finally {
    searching.value = false;
  }
};

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: "",
    content: "",
    userId: undefined,
    userName: "",
    articleId: undefined,
    ipAddress: "",
    status: undefined,
    isSensitive: undefined,
    sensitiveType: undefined,
    dateRange: null,
    minLikeCount: undefined,
    maxLikeCount: undefined,
    minReplyCount: undefined,
    maxReplyCount: undefined,
    sortField: "create_time",
    sortOrder: "desc",
    advancedOptions: [],
    size: 20
  });
  formRef.value?.clearValidate();
};

const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style scoped lang="scss">
.advanced-search {
  .el-form {
    .el-form-item {
      margin-bottom: 16px;
    }
  }

  .range-input {
    display: flex;
    align-items: center;
    width: 100%;
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
